import {
	WS_URL
} from "@/env.js"
import store from '@/store/index.js'
import http from "@/common/http.api.js"

class wsRequest {

	constructor(time, token) {
		this.status = null; // websocket是否关闭
		this.lockReconnect = false //避免重复连接
		this.url = WS_URL
		this.token = token

		//心跳检测
		this.timeout = time //多少秒执行检测
		this.timeoutObj = null //检测服务器端是否还活着
		this.reconnectTimeOutObj = null //重连之后多久再次重连

		try {
			return this.initRequest()
		} catch (e) {
			this.reconnect();
		}
	}

	initRequest() {
		this.socketTask = uni.connectSocket({
			url: this.url, //接口地址
			success: () => {
				console.log('连接成功');
				// 返回实例
				return this.socketTask
			}
		})

		this.socketTask.onOpen(res => {
			console.log(res, '连接打开');
			// 清除重连定时器
			clearTimeout(this.reconnectTimeOutObj)
			// 开启检测
			this.start()
		})

		this.socketTask.onClose((res) => {
			console.log(res, '连接关闭');
			this.reconnect();
		})

		this.socketTask.onError((res) => {
			console.log(res, '连接错误');
			this.reconnect();
		})

		this.socketTask.onMessage(res => {
			const getItem = JSON.parse(res.data)
			if (getItem.device_id) {
				const systemInfo = uni.getSystemInfoSync()
				if (systemInfo.deviceId !== getItem.device_id) {
					if (getItem.status === 1) {
						uni.navigateTo({
							url: '/pages/index/video/video'
						})
					} else {
						store.commit('common/SET_STATE', {
							key: ['id','isEnd'],
							value: [getItem.id,true]
						})
					}
				}
			}
			if (getItem.type === 'bind') {
				uni.request({
					url: `${http.allApi.baseUrl}/${http.allApi.userBind}`,
					method: 'POST',
					header: {
						'authtoken': this.token
					},
					data: {
						client_id: getItem.client_id
					},
					success(res) {
						if (res.statusCode == 200 && res.data.code == 1) {
						} else {
							uni.showToast({
								title: res.data.msg || res.errMsg || '获取信息失败',
								icon: 'none',
								mask: true
							})
						}
					},
					fail(fail) {
						
					},
					complete(e) {}
				})
			}
		})

	}

	send(value) {
		return new Promise((resovle, reject) => {
			this.socketTask.send({
				data: value,
				success: res => {
					resovle(value, '发送成功')
				}
			})
		})
	}

	// reset和start方法主要用来控制心跳的定时。
	reset() {
		// 清除定时器重新发送一个心跳信息
		clearTimeout(this.timeoutObj);
		this.start();
	}
	start() {
		this.timeoutObj = setTimeout(() => {
			//这里发送一个心跳，后端收到后，返回一个心跳消息，
			//onmessage拿到返回的心跳就说明连接正常
			this.socketTask.send({
				data: "ping"
			});

		}, this.timeout)
	}

	// 重连
	reconnect() {
		// 防止多个方法调用，多处重连
		if (this.lockReconnect) {
			return;
		};
		this.lockReconnect = true;

		console.log('准备重连');

		//没连接上会一直重连，设置延迟避免请求过多
		this.reconnectTimeOutObj = setTimeout(() => {
			// 重新连接
			this.initRequest()

			this.lockReconnect = false;
		}, 4000);
	}

	// 手动关闭
	close() {
		this.socketTask.close()
	}
}

module.exports = wsRequest